package link.chengguo.orangemall.single.oms;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import link.chengguo.orangemall.exception.ApiMallPlusException;
import link.chengguo.orangemall.oms.entity.OmsCartItem;
import link.chengguo.orangemall.oms.service.IOmsCartItemService;
import link.chengguo.orangemall.oms.service.IOmsOrderService;
import link.chengguo.orangemall.oms.vo.CartMarkingVo;
import link.chengguo.orangemall.oms.vo.CartProduct;
import link.chengguo.orangemall.oms.vo.OmsCartResult;
import link.chengguo.orangemall.pms.service.IPmsSkuStockService;
import link.chengguo.orangemall.pms.vo.GoodsDetailResult;
import link.chengguo.orangemall.single.ApiBaseAction;
import link.chengguo.orangemall.sms.entity.SmsBasicMarking;
import link.chengguo.orangemall.sms.service.ISmsBasicMarkingService;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.service.IUmsMemberService;
import link.chengguo.orangemall.util.JsonUtils;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.vo.Rediskey;
import link.chengguo.orangemall.vo.oms.CartParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车管理Controller
 * yzb 2019-12-26
 */
@RestController
@Api(tags = "购物车管理", description = "OmsCartItemController")
@RequestMapping("/api/oms/cart")
public class OmsCartItemController extends ApiBaseAction {
    @Autowired
    private IOmsCartItemService cartItemService;
    @Autowired
    private IUmsMemberService memberService;

    @Autowired
    private IPmsSkuStockService pmsSkuStockService;

    @Resource
    private IOmsOrderService orderService;
    @Resource
    private ISmsBasicMarkingService smsBasicMarkingService;

    @ApiOperation("添加商品到购物车")
    @PostMapping(value = "/addCart")
    @ResponseBody
    public Object addCart(CartParam cartParam) {
        try {
            if (cartParam.getCartType() == null) {
                cartParam.setCartType(0);
            }
            return orderService.addCart(cartParam);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("获取某个会员的购物车列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(OmsCartItem entity,Integer ifOtherCity) {
        UmsMember umsMember = memberService.getNewCurrentMember();
        Map<String, Object> map = new HashMap<>();
        List<OmsCartItem> cartItemList;
        if(ifOtherCity == 0){
            cartItemList = cartItemService.list(new QueryWrapper<OmsCartItem>().eq("member_id",umsMember.getId()).eq("city_code",entity.getCityCode()));
        }else{
            cartItemList = cartItemService.list(new QueryWrapper<OmsCartItem>().eq("member_id",umsMember.getId()).ne("city_code",entity.getCityCode()));
        }
        List<Long> shopIds = new ArrayList<>();
        for (OmsCartItem oc : cartItemList) {
            //shopIds.indexOf(oc.getShopId()) == -1判断商店id是否在列表中存在
            if (shopIds.indexOf(oc.getShopId()) == -1) {
                shopIds.add(oc.getShopId());
            }
        }
        List<OmsCartResult> results = new ArrayList<>();
        List<OmsCartItem> tmpList = null;
        for (Long id : shopIds) {
            tmpList = new ArrayList<>();
            OmsCartResult ocr = new OmsCartResult();
            ocr.setShopId(id);
            for (OmsCartItem item : cartItemList) {
                if (item.getShopId().longValue() == id.longValue()) {
                    tmpList.add(item);
                    ocr.setShopName(item.getShopName());
                }
            }
            ocr.setList(tmpList);
            results.add(ocr);
        }
        map.put("cartItemList", results);
        CartMarkingVo vo = new CartMarkingVo();
        vo.setCartList(cartItemList);
        SmsBasicMarking marking = smsBasicMarkingService.matchOrderBasicMarking(vo);
        if (marking != null) {
            map.put("promoteAmount", marking.getMinAmount());
        } else {
            map.put("promoteAmount", 0);
        }

        return new CommonResult().success(map);
    }

    @ApiOperation("获取每个店铺预结算总金额")
    @GetMapping(value = "/getPrice")
    @ResponseBody
    public Object getPrice(String ids) {
        String[] idsStr = ids.split(",");
        Map<String,Object> map = new HashMap<>();
        Long[] strArrNum = (Long[]) ConvertUtils.convert(idsStr,Long.class);
        List<OmsCartItem> list = cartItemService.list(new QueryWrapper<OmsCartItem>().in("id", strArrNum));
//        if(list.size()!=ids.size()){
//            return new CommonResult().failed("传入数据与后台不匹配");
//        }
        BigDecimal totalAmount  = cartItemService.calculationAmout(list);
        map.put("totalAmount",totalAmount);
        return new CommonResult().success(map);
    }
    @ApiOperation("获取某个会员某个店铺下的购物车列表")
    @RequestMapping(value = "/list/shop", method = RequestMethod.GET)
    @ResponseBody
    public Object listForShop(OmsCartItem cartItem) {
        if (cartItem.getCartType() == null) {
            cartItem.setCartType(0);//默认查询普通购物车。
        }
        UmsMember umsMember = memberService.getNewCurrentMember();
        Map<String, Object> map = new HashMap<>();
        if (umsMember != null && umsMember.getId() != null) {
            List<OmsCartItem> cartItemList = cartItemService.list(new QueryWrapper<OmsCartItem>().eq("member_id",umsMember.getId()).eq("shop_id",cartItem.getShopId()));
            map.put("cartItemList", cartItemList);
            CartMarkingVo vo = new CartMarkingVo();
            vo.setCartList(cartItemList);
            SmsBasicMarking marking = smsBasicMarkingService.matchOrderBasicMarking(vo);
            if (marking != null) {
                map.put("promoteAmount", marking.getMinAmount());
            } else {
                map.put("promoteAmount", 0);
            }

            return new CommonResult().success(map);
        }
        return new CommonResult().success(map);
    }


    @ApiOperation("修改购物车中某个商品的数量")
    @RequestMapping(value = "/update/quantity", method = RequestMethod.GET)
    @ResponseBody
    public Object updateQuantity(@RequestParam Long id,
                                 @RequestParam Integer quantity) {
        int count = cartItemService.updateQuantity(id, memberService.getNewCurrentMember().getId(), quantity);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("获取购物车中某个商品的规格,用于重选规格")
    @RequestMapping(value = "/getProduct/{productId}", method = RequestMethod.GET)
    @ResponseBody
    public Object getCartProduct(@PathVariable Long productId) {
        CartProduct cartProduct = cartItemService.getCartProduct(productId);
        return new CommonResult().success(cartProduct);
    }

    @ApiOperation("修改购物车中商品的规格")
    @RequestMapping(value = "/update/attr", method = RequestMethod.POST)
    @ResponseBody
    public Object updateAttr(OmsCartItem cartItem) {
        int count = cartItemService.updateAttr(cartItem);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("删除购物车中的某个商品")
    @PostMapping(value = "/delete")
    @ResponseBody
    public Object delete(String cart_id_list) {
        if (StringUtils.isEmpty(cart_id_list)) {
            return new CommonResult().failed("参数为空");
        }
        List<Long> resultList = new ArrayList<>(cart_id_list.split(",").length);
        for (String s : cart_id_list.split(",")) {
            resultList.add(Long.valueOf(s));
        }
        int count = cartItemService.delete(memberService.getNewCurrentMember().getId(), resultList);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }

    @ApiOperation("清空购物车")
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    @ResponseBody
    public Object clear(OmsCartItem item) {
        //默认清理线上购物车
        if (item.getCartType() == null) {
            item.setCartType(0);
        }
        System.out.println("【店铺ID】："+item.getShopId());
        int count = cartItemService.clear(item);
        if (count > 0) {
            return new CommonResult().success(count);
        }
        return new CommonResult().failed();
    }


}
